﻿// Author:  Marco van Wieren <mailto:mvwieren@gmail.com>
// Year:    2012
// License: Microsoft Public License (Ms-PL)

using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web;


namespace Mvw.SharePoint.Taxonomy.AutoTagging
{
    public partial class ResetWorkspacesList : LayoutsPageBase
    {
        public string PagePermissionFlagString;
        protected Button RunButton;
        protected CheckBox MustHaveWorkspaceTermInfo;

        protected override void OnInit(EventArgs e)
        {
            SPBasePermissions pagePermissionFlag = (SPBasePermissions)Enum.Parse(typeof(SPBasePermissions), PagePermissionFlagString.Replace("SPBasePermissions.", ""));
            // You can change the current setting by changing the following line in PopulateWorkspacesList.aspx: <%@Page PagePermissionFlagString="SPBasePermissions.ManageWeb"%>
            SPWeb web = SPContext.Current.Web;
            if (!web.DoesUserHavePermissions(pagePermissionFlag))
            {
                // build the access denied page
                SPUtility.Redirect(SPUtility.AccessDeniedPage + "?Source=" + SPHttpUtility.UrlKeyValueEncode(web.Site.MakeFullUrl(Request.RawUrl)),
                                   SPRedirectFlags.RelativeToLayoutsPage,
                                   HttpContext.Current);
            }
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RunButtonClick(object sender, EventArgs e)
        {
            try
            {
                SPContext.Current.Web.AllowUnsafeUpdates = true;
                HandleRunButtonClick();
            }
            catch (Exception ex)
            {
                this.ShowMessage(SPUtility.GetLocalizedString("$Resources:GLOBAL_ErrorMsgType", "SPM.Resources",
                    SPContext.Current.Web.Language), ex.Message, "red");
            }
            finally
            {
                SPContext.Current.Web.AllowUnsafeUpdates = false;
            }
        }

        private void HandleRunButtonClick()
        {
            // Get a reference to all site collections (optionally only those previously created by SharePoint Portal Manager)
            // below the current web application

            List<Guid> siteIds = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                siteIds = SPContext.Current.Site.WebApplication.GetSiteIdsForWebApplication(MustHaveWorkspaceTermInfo.Checked);

                if (siteIds == null)
                {
                    this.ShowMessage(SPUtility.GetLocalizedString("$Resources:GLOBAL_WarningMsgType", "SPM.Resources", SPContext.Current.Web.Language),
                        SPUtility.GetLocalizedString("$Resources:RWL_WarningNoSitesFound", "SPM.Resources", SPContext.Current.Web.Language),
                        "yellow");
                    return;
                }

                // Get a reference to the Workspaces list
                var workspacesList = SPContext.Current.Web.Lists.TryGetList("Workspaces");
                if (workspacesList == null)
                {
                    throw new WorkspacesListNotFoundException(SPUtility.GetLocalizedString("$Resources:GLOBAL_ErrorWorkspacesListNotFound",
                        "SPM.Resources", SPContext.Current.Web.Language));
                }

                // Obtain a reference to the content type used for the Workspaces list 
                var ctWorkspace = SPContext.Current.Web.ContentTypes["Managed Workspace"];
                if (ctWorkspace == null)
                {
                    throw new WorkspacesContentTypeNotFoundException(SPUtility.GetLocalizedString("$Resources:GLOBAL_ErrorWorkspaceContentTypeNotFound",
                        "SPM.Resources", SPContext.Current.Web.Language));
                }

                // Add all AutoTagging Inheritable Columns to the Managed Workspace content type (used by the Workspaces List)
                var fields = SPContext.Current.Web.AvailableInheritableColumns();
                if (fields.Count <= 0)
                {
                    // Warn the user in case no columns are found
                    this.ShowMessage(SPUtility.GetLocalizedString("$Resources:GLOBAL_WarningMsgType", "SPM.Resources", SPContext.Current.Web.Language),
                        SPUtility.GetLocalizedString("$Resources:RWL_WarningNoInheritableColumnsFound", "SPM.Resources", SPContext.Current.Web.Language),
                        "yellow");
                    return;
                }

                foreach (var field in fields)
                {
                    if (ctWorkspace.FieldLinks[field.Id] == null)
                    {
                        ctWorkspace.FieldLinks.Add(new SPFieldLink(field));
                    }
                }
                ctWorkspace.Update(true);

                // Now create new list items using the site collection ids we've collected previously
                var listEntriesAdded = workspacesList.ResetAndPopulate(siteIds);

                // And report back to the user how many Workspaces were added
                this.ShowMessage(SPUtility.GetLocalizedString("$Resources:GLOBAL_InfoMsgType", "SPM.Resources", SPContext.Current.Web.Language),
                    listEntriesAdded + SPUtility.GetLocalizedString("$Resources:RWL_InfoMsgText", "SPM.Resources", SPContext.Current.Web.Language),
                    "green");
            });
        }
    }
}
